#!/bin/python3
import os
import sys
import time
import random
import curses

def main(screen):
    curses.curs_set(0)  # 隐藏光标
    screen_height, screen_width = screen.getmaxyx()

    # 定义棋盘大小
    BOARD_WIDTH = 10
    BOARD_HEIGHT = 8

    # 定义玩家位置
    player_x = 0
    player_y = 0

    # 定义移动方向
    directions = [ (1, 0),(0, 1), (-1, 0), (0, -1)]  # 分别代表向右、向下、向左\ 向上、移动
    direction_index = 0  # 当前移动方向的索引

    # 游戏主循环
    lap_count = 0
    while lap_count < 2:
        # 获取键盘输入
        key = screen.getch()

        # 如果按下数字键,抛骰子
        if ord('1') <= key <= ord('6'):
            num_dice = key - ord('0')
            dice_values = [random.randint(1, 6) for _ in range(num_dice)]
            dice_values = [1]
            screen.addstr(screen_height - 1, 0, "骰子点数: " + ', '.join(map(str, dice_values)) + ' ')

            # 计算总移动步数
            total_steps = sum(dice_values)

            # 移动玩家
            for _ in range(total_steps):
                dx, dy = directions[direction_index]
                new_x = player_x + dx
                new_y = player_y + dy

                # 检查是否需要转向或撞墙
                if new_x < 0 or new_x >= BOARD_WIDTH or new_y < 0 or new_y >= BOARD_HEIGHT:
                    direction_index = (direction_index + 1) % 4  # 改变方向
                    dx, dy = directions[direction_index]
                    new_x = player_x + dx
                    new_y = player_y + dy

                player_x = new_x
                player_y = new_y

        # 绘制棋盘
        screen.clear()
        for y in range(BOARD_HEIGHT):
            for x in range(BOARD_WIDTH):
                if x == player_x and y == player_y:
                    screen.addch(y, x, '@')
                elif x == 0 or x == BOARD_WIDTH - 1 or y == 0 or y == BOARD_HEIGHT - 1:
                    screen.addch(y, x, '#')
                else:
                    screen.addch(y, x, ' ')

        # 检查是否绕了一圈
        # if player_x == 0 and player_y == 0 and (dx, dy) == directions[0]:  # 只有在初始方向下才计算圈数
        #     lap_count += 1
        # 检查是否绕了一圈
        if player_x == 0 and player_y == 0 and direction_index == 0:  # 只有在初始方向（向下移动）下才计算圈数
            lap_count += 1

        screen.refresh()
        time.sleep(0.1)  # 延时0.1秒,控制移动速度

    curses.endwin()
    print("游戏结束!")

curses.wrapper(main)
